<template>
  <view class="container">
    <!-- 优惠券列表 -->
    <view class="coupon-list">
      <!-- 不使用优惠券选项 -->
      <view class="coupon-item no-coupon" :class="!selectedCoupon ? 'coupon-selected' : ''" @tap="selectNoCoupon">
        <view class="coupon-content">
          <view class="coupon-left">
            <view class="coupon-icon">🚫</view>
            <view class="coupon-info">
              <text class="coupon-name">不使用优惠券</text>
              <text class="coupon-desc">直接使用原价支付</text>
            </view>
          </view>
          <view class="coupon-right">
            <view class="radio-btn" :class="!selectedCoupon ? 'radio-active' : ''">
              <text v-if="!selectedCoupon" class="radio-check">✓</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 优惠券列表 -->
      <view v-for="(couponItem, index) in couponList" :key="couponItem.id" class="coupon-item" :class="{
        'coupon-selected': selectedCoupon && selectedCoupon.coupon_id === couponItem.coupon_id,
        'coupon-disabled': !isCouponAvailable(couponItem)
      }" @tap="selectCoupon(couponItem)">
        <view class="coupon-content">
          <view class="coupon-left">
            <view class="coupon-amount">
              <text class="amount-symbol">¥</text>
              <text class="amount-value">{{ couponItem.coupon.amount }}</text>
            </view>
            <view class="coupon-info">
              <text class="coupon-name">{{ getCouponName(couponItem) }}</text>
              <text class="coupon-desc">满{{ couponItem.coupon.min_consumption }}可用</text>
              <text class="coupon-validity">有效期至：{{ formatDate(couponItem.coupon.end_time) }}</text>
            </view>
          </view>
          <view class="coupon-right">
            <view v-if="isCouponAvailable(couponItem)" class="radio-btn"
              :class="selectedCoupon && selectedCoupon.coupon_id === couponItem.coupon_id ? 'radio-active' : ''">
              <text v-if="selectedCoupon && selectedCoupon.coupon_id === couponItem.coupon_id" class="radio-check">✓</text>
            </view>
            <view v-else class="unavailable-tag">
              <text class="unavailable-text">不可用</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="couponList.length === 0 && !isLoading">
        <view class="empty-icon">🎫</view>
        <text class="empty-text">暂无可用优惠券</text>
        <text class="empty-desc">快去获取更多优惠券吧</text>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="isLoading">
        <text class="loading-text">加载中...</text>
      </view>
    </view>

    <!-- 底部确认按钮 -->
    <view class="bottom-bar">
      <view class="price-info">
        <text class="original-price">订单金额：¥{{ totalPrice.toFixed(2) }}</text>
        <text v-if="selectedCoupon" class="final-price">优惠后：¥{{ finalPrice.toFixed(2) }}</text>
      </view>
      <button class="confirm-btn" @tap="confirmSelection">确认选择</button>
    </view>
  </view>
</template>

<script>
import request from '@/common/request.js';

export default {
  data() {
    return {
      couponList: [],
      selectedCoupon: null,
      totalPrice: 0,
      roomId: '',
      shopId: '',
      params: {},
      isLoading: false,
      orderData: {}
    }
  },
  computed: {
    finalPrice() {
      let price = this.totalPrice;
      if (this.selectedCoupon && this.selectedCoupon.coupon) {
        price = Math.max(0, price - parseFloat(this.selectedCoupon.coupon.amount || 0));
      }
      return price;
    }
  },
  onLoad(options) {
    console.log('优惠券页面接收参数:', options);
    // 解析传入的参数
    if (options.params) {
      try {
        this.params = JSON.parse(decodeURIComponent(options.params));
        console.log('解析后的参数:', this.params);
        this.totalPrice = parseFloat(this.params.totalPrice || 0);
        this.roomId = this.params.roomId || '';
        this.shopId = this.params.shopId || '';
        this.orderData = this.params.orderData || {};
      } catch (e) {
        console.error('解析参数失败:', e);
      }
    }
    // 接收已选择的优惠券（从其他页面返回时）
    if (options.selectedCoupon) {
      try {
        this.selectedCoupon = JSON.parse(decodeURIComponent(options.selectedCoupon));
        console.log('已选择的优惠券:', this.selectedCoupon);
      } catch (e) {
        console.error('解析已选优惠券失败:', e);
      }
    }
    this.getCouponList();
  },
  methods: {
    // 获取优惠券列表
    getCouponList(isRefresh = false) {
      if (!this.roomId) {
        uni.showToast({
          title: '房间信息缺失',
          icon: 'none'
        });
        return;
      }
      
      this.isLoading = true;
      let opts = {
        url: `/api/shop/getUserCouponByRoom?room_id=${this.roomId}`,
        method: 'get',
      };

      request.httpTokenRequest(opts).then(res => {
        console.log('获取优惠券列表响应:', res);
        this.isLoading = false;

        if (res && res.data && res.data.code == 1) {
          const newCoupons = res.data.data || [];
          this.couponList = newCoupons;
          console.log('优惠券列表:', this.couponList);
        } else {
          uni.showToast({
            title: res.data?.msg || '获取优惠券失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        this.isLoading = false;
        console.error('获取优惠券列表失败:', err);
        uni.showToast({
          title: '获取优惠券失败',
          icon: 'none'
        });
      });
    },

    // 获取优惠券名称
    getCouponName(couponItem) {
      // 如果有room_name，解析并显示
      if (couponItem.room_name) {
        try {
          const roomNames = JSON.parse(couponItem.room_name);
          if (Array.isArray(roomNames) && roomNames.length > 0) {
            return `${roomNames[0]}专用券`;
          }
        } catch (e) {
          console.error('解析房间名称失败:', e);
        }
      }

      // 默认显示优惠券金额
      return `${couponItem.coupon.amount}元优惠券`;
    },

    // 判断优惠券是否可用
    isCouponAvailable(couponItem) {
      console.log('判断优惠券可用性:', couponItem);

      // 检查优惠券状态
      if (couponItem.status !== "1") {
        console.log('优惠券状态不可用:', couponItem.status);
        return false;
      }

      // 检查最低消费金额
      const minConsumption = parseFloat(couponItem.coupon.min_consumption || 0);
      if (minConsumption > 0 && this.totalPrice < minConsumption) {
        console.log('订单金额不满足最低消费:', this.totalPrice, '<', minConsumption);
        return false;
      }

      // 检查有效期 (end_time是时间戳)
      if (couponItem.coupon.end_time) {
        const expireTime = new Date(couponItem.coupon.end_time * 1000);
        const now = new Date();
        if (expireTime < now) {
          console.log('优惠券已过期:', expireTime, '<', now);
          return false;
        }
      }

      // 检查开始时间 (start_time是时间戳)
      if (couponItem.coupon.start_time) {
        const startTime = new Date(couponItem.coupon.start_time * 1000);
        const now = new Date();
        if (startTime > now) {
          console.log('优惠券未到使用时间:', startTime, '>', now);
          return false;
        }
      }

      console.log('优惠券可用');
      return true;
    },

    // 选择优惠券
    selectCoupon(couponItem) {
      console.log('选择优惠券:', couponItem);
      
      if (!this.isCouponAvailable(couponItem)) {
        uni.showToast({
          title: '该优惠券不可用',
          icon: 'none'
        });
        return;
      }

      // 检查是否是取消选择
      if (this.selectedCoupon && this.selectedCoupon.coupon_id === couponItem.coupon_id) {
        console.log('取消选择优惠券');
        this.selectedCoupon = null;
      } else {
        // 选择优惠券，转换数据格式以兼容原有逻辑
        this.selectedCoupon = {
          id: couponItem.id, // 用户优惠券记录ID
          coupon_id: couponItem.coupon_id, // 优惠券模板ID
          name: this.getCouponName(couponItem),
          discount: couponItem.coupon.amount,
          amount: couponItem.coupon.amount,
          min_consumption: couponItem.coupon.min_consumption,
          coupon: couponItem.coupon,
          originalData: couponItem // 保存原始数据
        };
        console.log('已选择优惠券:', this.selectedCoupon);
      }
    },

    // 选择不使用优惠券
    selectNoCoupon() {
      console.log('选择不使用优惠券');
      this.selectedCoupon = null;
    },

    // 确认选择
    confirmSelection() {
      console.log('确认选择，当前选中:', this.selectedCoupon);
      
      // 构建返回参数
      const returnParams = {
        ...this.params
      };

      if (this.selectedCoupon) {
        returnParams.selectedCoupon = encodeURIComponent(JSON.stringify(this.selectedCoupon));
      } else {
        // 确保清除之前选择的优惠券
        delete returnParams.selectedCoupon;
      }

      console.log('返回参数:', returnParams);

      // 获取页面栈 - uni-app中getCurrentPages是全局函数
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];

      if (prevPage) {
        console.log('返回到页面:', prevPage.route);
        
        // 构建返回URL
        const paramString = Object.keys(returnParams)
          .filter(key => returnParams[key] !== undefined && returnParams[key] !== null)
          .map(key => `${key}=${returnParams[key]}`)
          .join('&');

        const returnUrl = `/${prevPage.route}${paramString ? '?' + paramString : ''}`;
        console.log('返回URL:', returnUrl);

        uni.redirectTo({
          url: returnUrl,
          success: () => {
            console.log('返回成功');
          },
          fail: (err) => {
            console.error('返回失败:', err);
            // 如果redirectTo失败，尝试使用navigateBack
            uni.navigateBack({
              delta: 1
            });
          }
        });
      } else {
        console.log('没有上一页，直接返回');
        uni.navigateBack({
          delta: 1
        });
      }
    },

    // 格式化日期 (处理时间戳)
    formatDate(timestamp) {
      if (!timestamp) return '';

      const date = new Date(timestamp * 1000); // 转换为毫秒
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    },

    // 返回
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 200rpx;
}

.coupon-list {
  padding: 20rpx;
}

.coupon-item {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
  position: relative;

  &.coupon-selected {
    border: 4rpx solid #007aff;
    background-color: #f0f8ff;
  }

  &.coupon-disabled {
    opacity: 0.5;
    background-color: #f8f8f8;
  }

  &.no-coupon {
    border: 2rpx solid #e0e0e0;

    &.coupon-selected {
      border-color: #007aff;
      background-color: #f0f8ff;
    }
  }
}

.coupon-content {
  display: flex;
  align-items: center;
  padding: 30rpx;
}

.coupon-left {
  flex: 1;
  display: flex;
  align-items: center;
}

.coupon-amount {
  display: flex;
  align-items: baseline;
  margin-right: 30rpx;
  min-width: 120rpx;
}

.amount-symbol {
  font-size: 24rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.amount-value {
  font-size: 48rpx;
  color: #ff6b6b;
  font-weight: bold;
}

.coupon-icon {
  font-size: 48rpx;
  margin-right: 30rpx;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.coupon-desc {
  font-size: 28rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.coupon-validity {
  font-size: 24rpx;
  color: #999;
  display: block;
}

.coupon-right {
  display: flex;
  align-items: center;
}

.radio-btn {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
}

.radio-active {
  border-color: #007aff;
  background-color: #007aff;
}

.radio-check {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.unavailable-tag {
  padding: 8rpx 16rpx;
  background-color: #f0f0f0;
  border-radius: 20rpx;
}

.unavailable-text {
  font-size: 24rpx;
  color: #999;
}

.empty-state, .loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 40rpx;
  opacity: 0.3;
}

.empty-text, .loading-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 16rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: #999;
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 30rpx;
  border-top: 2rpx solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.price-info {
  display: flex;
  flex-direction: column;
}

.original-price {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.final-price {
  font-size: 28rpx;
  font-weight: bold;
  color: #ff6b6b;
}

.confirm-btn {
  background-color: #007aff;
  color: #fff;
  border: none;
  padding: 0 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  font-weight: 500;
  margin: 0;
}
</style>